package com.aube.interact.fighter;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.aube.interact.fighter.model.CategoryImp;
import com.aube.interact.fighter.model.CategoryListModel;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.model.Category;
import com.huyn.baseframework.model.ChannelDetail;
import com.huyn.baseframework.model.VideoModel;
import com.huyn.baseframework.net.BFJSONRequest;
import com.huyn.baseframework.net.HttpRequestLoader;
import com.huyn.baseframework.net.OpenApi;
import com.huyn.baseframework.utils.SysUtil;
import com.huyn.baseframework.utils.Utils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by hill on 16/12/16.
 */
public class RecommendedVideosLayout extends FrameLayout {
    private final String TAG = "Aube/AutoPlayView";

    private Context mContext;

    private IPluginBaseListener mBaseListener;
    private Category mCategory;
    private ChannelDetail mChannelDetail;

    private Handler mHandler =new Handler();
    private ChannelDetail mNextEpisodeDetail;

    private int mCountDown = 4;

    private LinearLayout mReplayLy;
    private LinearLayout mVideosLy, mCheckGoodsLy;

    private TextView mTimerText, mNextVideoTitle;

    private AtomicBoolean mCallSended = new AtomicBoolean(false);

    public RecommendedVideosLayout(Context context) {
        this(context, null);
    }
    public RecommendedVideosLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public RecommendedVideosLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        initView();
    }

    private void initView() {
        Utils.Log(TAG, "[initView]");
        LayoutInflater.from(mContext).inflate(R.layout.aube_intera_recommend_video, this);
        mReplayLy = (LinearLayout) findViewById(R.id.autoplay_replay);
        mVideosLy = (LinearLayout) findViewById(R.id.autoplay_videos_layout);
        mTimerText = (TextView) findViewById(R.id.autoplay_timertext);
        mCheckGoodsLy = (LinearLayout) findViewById(R.id.autoplay_checkgoods);
        mNextVideoTitle = (TextView) findViewById(R.id.autoplay_videoname);

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        mCheckGoodsLy.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                alphaOut();
            }
        });

        mReplayLy.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mBaseListener != null)
                    mBaseListener.switchVideo(mChannelDetail);
            }
        });
    }

    public void alphaIn() {
        if(mNextEpisodeDetail == null) {
            mNextVideoTitle.setVisibility(View.GONE);
            mTimerText.setText("视频播放完了~");
        } else {
            mTimerText.setText("5 秒后自动播放下一集");
            mNextVideoTitle.setVisibility(View.VISIBLE);
            mNextVideoTitle.setText(mNextEpisodeDetail.videoTitle);
        }
        ObjectAnimator animator = ObjectAnimator.ofFloat(this, "alpha", 0f, 1f);
        animator.setDuration(300);
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                setVisibility(VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if(mNextEpisodeDetail != null) {
                    playNextVideoAfter5s();
                }
            }
        });
        animator.start();
    }

    private void alphaOut() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(this, "alpha", 1f, 0f);
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                setVisibility(GONE);
                if(mBaseListener != null)
                    mBaseListener.showGoodsStore();
            }
        });
        animator.setDuration(300);
        animator.start();
    }

    public void setupContent(Category category, ChannelDetail channelDetail, IPluginBaseListener listner) {
        mBaseListener = listner;

        mCategory = category;
        mChannelDetail = channelDetail;

        if(listner.hasGoodsInStore())
            mCheckGoodsLy.setVisibility(View.VISIBLE);
    }

    /**
     * 模块内容接口
     * templateCode(index | actor)
     * ostype(iphone|android)
     * modelCode（template接口中获取）
     * relatedId（有就传，比如嘉宾）
     * lastId（分页用，第一次可不传，当前页最后一个id）
     * maxnum（一页最大条数）
     */
    public void fetchServerData() {
        if(mCallSended.get())
            return;
        mCallSended.set(true);

        if(mCategory == null) {
            Utils.Log(TAG, "[fetchServerData] category is null");
            return;
        }

        if(mVideosLy.getChildCount() > 0)
            return;

        HashMap<String, String> params = new HashMap<>();
        params.put(OpenApi.API_METHOD, OpenApi.MODULE_MORE);
        params.put("templateCode", mCategory.templateType);
        params.put("modelCode", mCategory.modelCode);
        params.put("relatedId", mCategory.relatedId);
        params.put("maxnum", "10");
        params.put("subModelCode", mCategory.subModelCode);
        BFJSONRequest request = new BFJSONRequest(CategoryListModel.class, params, new Response.Listener<CategoryListModel>() {

            @Override
            public void onResponse(CategoryListModel response) {
                if(response == null || !response.success())
                    return;
                setupServerData(response);
            }

            @Override
            public void onErrorResponse(VolleyError error) {
            }

            @Override
            public void onStart() {
            }
        });
        HttpRequestLoader.getInstance(mContext).startCacheLoader("", request, true);
    }

    public void setupServerData(CategoryListModel model) {
        if(model == null || model.size() <= 0) {
            Utils.Log(TAG, "[setupServerData] model is null");
            return;
        }

        int width = SysUtil.getAbsoluteScreenWidth(getContext());
        int space = getResources().getDimensionPixelOffset(R.dimen.video_margin);
        int itemWidth = (width-3*space)/4;

        int i = 0;
        for(CategoryImp categoryImp : model.data) {
            if(categoryImp.modelCode.equalsIgnoreCase("modelHead"))
                continue;

            if(!categoryImp.subModelCode.equalsIgnoreCase(mCategory.subModelCode))
                continue;

            HashMap<String, VideoModel> mRecommendMap = new HashMap<>();
            int mRecommendSize=0;
            boolean mAfterCurrent = false;

            for(Object obj : categoryImp.dataDetail) {
                final VideoModel videoModel = new VideoModel();

                LinkedHashMap<String, Object> lhm = (LinkedHashMap<String, Object>) obj;
                Iterator<String> keyIterator= lhm.keySet().iterator();
                while (keyIterator.hasNext()) {
                    String key = keyIterator.next();
                    Object value = lhm.get(key);
                    videoModel.setItem(key, value);
                }

                if(!mChannelDetail.videoid.equalsIgnoreCase(videoModel.videoid)) {
                    if(mAfterCurrent) {
                        mNextEpisodeDetail = videoModel.toChannelDetail();
                        mAfterCurrent = false;
                    } else {
                        if (mRecommendSize < 4) {
                            mRecommendMap.put(videoModel.videoid, videoModel);
                            mRecommendSize++;
                        }
                    }
                } else {
                    mAfterCurrent = true;
                }
            }

            if(mRecommendMap.size() > 0) {
                Iterator<VideoModel> valueIterator = mRecommendMap.values().iterator();
                int size = 0;
                while (valueIterator.hasNext()) {
                    if(size >= 3)
                        return;
                    VideoModel item = valueIterator.next();

                    inflateVideoItem(item, itemWidth);

                    if(size == 2 || size == mRecommendMap.size()-1) {
                        return;
                    }

                    mVideosLy.addView(new View(mContext), new LinearLayout.LayoutParams(space, itemWidth * 3 / 4));

                    size++;
                }
                return;
            }
        }
    }

    private void inflateVideoItem(final VideoModel item, int itemWidth) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.aube_intera_item_video, null, false);
        ImageView mImg = (ImageView) view.findViewById(R.id.video_img);
        TextView mText = (TextView) view.findViewById(R.id.video_title);
        TextView mDes = (TextView) view.findViewById(R.id.video_des);
        View mImgGroup = view.findViewById(R.id.video_img_group);

        mText.setText(item.videoTitle);
        mDes.setText(item.videoDesc);
        mImg.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.bk_default));

        ImageLoader.getInstance(mContext).fillImage(mImg, item.pic, 400, 400);

        mVideosLy.addView(view, new LinearLayout.LayoutParams(itemWidth, ViewGroup.LayoutParams.WRAP_CONTENT));

        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mImgGroup.getLayoutParams();
        params.width = itemWidth;
        params.height = itemWidth*9/16;
        mImgGroup.setLayoutParams(params);

        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mBaseListener != null)
                    mBaseListener.switchVideo(item.toChannelDetail());
            }
        });
    }

    private void playNextVideoAfter5s() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(mCountDown > 0) {
                    mTimerText.setText(String.valueOf(mCountDown--) + " 秒后自动播放下一集");
                    playNextVideoAfter5s();
                } else {
                    if(mBaseListener != null)
                        mBaseListener.switchVideo(mNextEpisodeDetail);
                }

            }
        }, 1000);
    }

    public interface IPluginBaseListener {
        public void switchVideo(ChannelDetail detail);
        public void showGoodsStore();
        public boolean hasGoodsInStore();
    }

}
